package org.pine.common.components;

import cn.hutool.core.collection.CollUtil;
import org.pine.common.beans.OperateLogBody;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 操作日志上下文
 *
 * @author pine
 * @version v1.0
 * @since 2025-04-28 21:10
 */
public class OperateLogContext {

    /**
     * 日志上下文-threadLocal
     */
    private static final ThreadLocal<List<OperateLogBody>> OPERATE_LOG_BODY_THREAD_LOCAL = new InheritableThreadLocal<>();

    /**
     * 添加日志上下文
     *
     * @param log 日志上下文
     */
    public static void add(OperateLogBody log) {
        List<OperateLogBody> operateLogBodies = OPERATE_LOG_BODY_THREAD_LOCAL.get();
        if (operateLogBodies == null) {
            operateLogBodies = new ArrayList<>();
            OPERATE_LOG_BODY_THREAD_LOCAL.set(operateLogBodies);
        }
        operateLogBodies.add(log);
    }

    /**
     * 批量添加日志上下文
     *
     * @param logs 日志上下文列表
     */
    public static void add(List<OperateLogBody> logs) {
        List<OperateLogBody> operateLogBodies = OPERATE_LOG_BODY_THREAD_LOCAL.get();
        if (operateLogBodies == null) {
            operateLogBodies = new ArrayList<>();
            OPERATE_LOG_BODY_THREAD_LOCAL.set(operateLogBodies);
        }
        operateLogBodies.addAll(logs);
    }


    /**
     * 获取日志上下文
     *
     * @return 日志上下文列表
     */
    public static List<OperateLogBody> get() {
        List<OperateLogBody> operateLogBodies = OPERATE_LOG_BODY_THREAD_LOCAL.get();
        if (CollUtil.isEmpty(operateLogBodies)) {
            return Collections.emptyList();
        }
        return operateLogBodies;
    }


    /**
     * 清空日志上下文
     */
    public static void clear() {
        OPERATE_LOG_BODY_THREAD_LOCAL.remove();
    }
}
